package com.gxuwz.stats.service.excelhandler;

import com.alibaba.excel.EasyExcel;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.service.SheetHandler;
import com.gxuwz.stats.service.SheetName;
import com.gxuwz.stats.service.impl.UserServiceImpl;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Service
@SheetName("用户")
public class UserHandler implements SheetHandler {
    @Autowired
    private UserServiceImpl userService;

    private InputStream convertSheetToInputStream(Sheet sheet) {
        try {
            Workbook workbook = sheet.getWorkbook();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            workbook.write(out);
            return new ByteArrayInputStream(out.toByteArray());
        } catch (IOException e) {
            throw new RuntimeException("Sheet转换输入流失败", e);
        }
    }

    @Override
    public ImportResultProvider handle(Sheet sheet, String username, String role, String department) {
        InputStream inputStream = convertSheetToInputStream(sheet);
        String sheetName = sheet.getSheetName();

        UserListener listener = new UserListener(userService, username, role, department);

        if (sheetName != null && !sheetName.trim().isEmpty() && !sheetName.trim().toLowerCase().startsWith("sheet")) {
            EasyExcel.read(inputStream, User.class, listener)
                    .sheet(sheetName)
                    .headRowNumber(1)
                    .doRead();
        } else {
            EasyExcel.read(inputStream, User.class, listener)
                    .sheet()
                    .headRowNumber(1)
                    .doRead();
        }
        return listener;
    }
}